﻿using EFCore.Models;
using Microsoft.EntityFrameworkCore;
using SIService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace SService
{
    public class InboundS : InboundSI
    {
        private readonly WmssystemContext myDb;

        public InboundS(WmssystemContext myDb)
        {
            this.myDb = myDb;
        }

        public Task<int> Add(PO_Inbound pO_Inbound)
        {
            myDb.PO_Inbound.Add(pO_Inbound);
            return myDb.SaveChangesAsync();
        }

        public Task<List<PO_Inbound>> Fye(int pageSize, int currentPage, string Number=null, string Type = null, string Status = null, string WName = null)
        {
           
            var query = myDb.PO_Inbound.AsQueryable();

            // 根据条件进行查询
            if (!string.IsNullOrEmpty(Number))
            {
                query = query.Where(c => c.I_InboundCode.Contains(Number.Trim()));
            }
            if (!string.IsNullOrEmpty(Type))
            {
                query = query.Where(c => c.I_InboundType == Type);
            }
            if (!string.IsNullOrEmpty(Status))
            {
                query = query.Where(c => c.I_InboundStatus == Status);
            }
            if (!string.IsNullOrEmpty(WName))
            {
                query = query.Where(c => c.I_WarehouseName == WName);
            }

           


            // 分页查询
            return query.Skip((currentPage - 1) * pageSize).Take(pageSize).ToListAsync();
        }

        public async Task<List<PO_Purchaseorders>> Jhqu()
        {
            // 两个表连接查询，并过滤掉 P_OStatus 为 "已入库" 的记录
            var  query = from purchaseOrder in myDb.PO_Purchaseorders
                         join supplier in myDb.Su_Suppliermanagement
                         on purchaseOrder.P_OSupplier equals supplier.S_MIndex.ToString()
                        join Org in myDb.Sys_OrganizationalStructure
                         on purchaseOrder.P_OPurchasingDepartment equals Org.O_SSerialId.ToString()
                        //where purchaseOrder.P_OStatus != "已入库"&& purchaseOrder.P_OStatus!= "待审核"
                         select new PO_Purchaseorders
                        {
                            P_OSupplier = supplier.S_MSupplierName,
                            P_OIndex = purchaseOrder.P_OIndex,
                            P_OOrderNumber = purchaseOrder.P_OOrderNumber,
                            P_OStatus = purchaseOrder.P_OStatus,
                            P_ODate = purchaseOrder.P_ODate,
                            P_OPurchasingDepartment = Org.O_SOrganizationName,
                            P_OPurchaser = supplier.S_MPurchasingRepresentative,
                            P_OQuantity = purchaseOrder.P_OQuantity,
                            P_OAmount = purchaseOrder.P_OAmount,
                            P_OContactPerson = purchaseOrder.P_OContactPerson,
                            P_OContactInformation = purchaseOrder.P_OContactInformation,
                            P_OPurchased = purchaseOrder.P_OPurchased,
                            P_OCreator = purchaseOrder.P_OCreator,
                            P_ODepartment = purchaseOrder.P_ODepartment,
                            P_OCreationTime = purchaseOrder.P_OCreationTime,
                        };

            var result = await query.ToListAsync();
            return result;
        }

        public Task<List<PO_Inbound>> Qu()
        {
            return myDb.PO_Inbound.ToListAsync();
        }

        public async Task<int> RkDel(List<int> Ids)
        {
            // 使用 LINQ 查询语句检索相应的记录
            var detailsToDelete = await myDb.PO_Inbound
                .Where(d => Ids.Contains(d.I_InboundIndex))
                .ToListAsync();

            // 删除查询结果
            myDb.PO_Inbound.RemoveRange(detailsToDelete);

            // 保存删除操作到数据库
            return await myDb.SaveChangesAsync();
        }

        public async  Task<int> RkShen(PO_Inbound pO_Inbound, string to)
        {
            // 1. 根据指定条件查找要审核的记录
            var purchaseOrder = await myDb.PO_Inbound.FindAsync(pO_Inbound.I_InboundIndex);

            if (purchaseOrder == null)
            {
                // 如果没有找到对应的记录，可以进行适当的处理，比如抛出异常或者返回错误码
                throw new Exception("指定的记录不存在");
            }
            if (to == "通过")
            {
                purchaseOrder.I_InboundStatus = "未出库";
                //把入库的数量回写到进货明细表中
                var ppList = await myDb.PO_Inventorydetails.Where(c => c.I_InboundCode == purchaseOrder.I_InboundCode).ToListAsync();
                foreach (var pp in ppList)
                {
                    var ccList = await myDb.PO_Purchasedetails.Where(c => c.P_DProductCode == pp.I_IProductCode).ToListAsync();
                    foreach (var cc in ccList)
                    {
                        cc.P_DQuantity = (int?)(cc.P_DQuantity - pp.I_IQuantity);
                        // 如果需要更新其他属性，也可以在这里进行修改
                    }
                }
            }
            else
            {
                purchaseOrder.I_InboundStatus = "未审核";
            }
            // 2. 更新找到的记录的相应字段
            purchaseOrder.I_Approver = "admin"; // 以此类推，更新需要修改的字段
            purchaseOrder.I_ApprovalTime = DateTime.Now;
            purchaseOrder.P_Reviewcomments = pO_Inbound.P_Reviewcomments;


            // 3. 将更新后的记录保存回数据库中
            myDb.PO_Inbound.Update(purchaseOrder);
            return await myDb.SaveChangesAsync(); // 返回受影响的行数
        }

        public async Task<int> Upd(PO_Purchaseorders pO_Purchaseorders)
        {
            var existingOrder = await myDb.PO_Purchaseorders .FirstOrDefaultAsync(o => o.P_OOrderNumber == pO_Purchaseorders.P_OOrderNumber.Trim());
            // 检查订单是否存在
            if (existingOrder == null)
            {
                return 0; // 表示未找到要更新的订单
            }
            existingOrder.P_OStatus = pO_Purchaseorders.P_OStatus;
            return await myDb.SaveChangesAsync();
        }

        public async Task<int> Upd1(PO_Inbound pO_Inbound)
        {
            var existingOrder = await myDb.PO_Inbound.FirstOrDefaultAsync(o => o.I_InboundIndex == pO_Inbound.I_InboundIndex);
            // 检查订单是否存在
            if (existingOrder == null)
            {
                return 0; // 表示未找到要更新的订单
            }
            existingOrder.I_InboundType = pO_Inbound.I_InboundType;
            existingOrder.I_WarehouseName = pO_Inbound.I_WarehouseName;
            existingOrder.I_InboundDate = pO_Inbound.I_InboundDate;
            existingOrder.I_AssociatedCode = pO_Inbound.I_AssociatedCode;
            existingOrder.I_OSupplier = pO_Inbound.I_OSupplier;
            existingOrder.I_OContactPerson = pO_Inbound.I_OContactPerson;
            existingOrder.I_OContactInformation = pO_Inbound.I_OContactInformation;
            existingOrder.I_Handler = pO_Inbound.I_Handler;
            existingOrder.I_Reamr = pO_Inbound.I_Reamr;
           
            return await myDb.SaveChangesAsync();
        }
    }
}
